package com.xxl.job.executor.service.jobhandler;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobContext;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.mybatis.service.JobUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.xxl.job.core.handler.IJobHandler.SUCCESS;

/**
 * @author: 吴多强
 * @description: 分片批量删除
 **/
@Component
public class ShardingBatchDelete {
    private static Logger logger = LoggerFactory.getLogger(ShardingBatchDelete.class);
    @Resource
    private JobUserService jobUserService;

    @XxlJob("ShardingBatchDelete")
    public ReturnT<String> shardingJobHandler(String param) throws Exception {
        // 当前分片序号
        int shardIndex = XxlJobContext.getXxlJobContext().getShardIndex() + 1;
        // 总分片数
        int shardTotal = XxlJobContext.getXxlJobContext().getShardTotal();
        // 总的分片任务
        int taskAll = Integer.parseInt(param);
        // 平均分片个数
        int avg = taskAll / shardTotal;
        logger.info("当前分片序号" + shardIndex + " 总分片数" + shardTotal + "总的分片任务" + taskAll + "平均分片个数" + avg);
        // 开始数
        int start = shardIndex == 1 ? 1 : (shardIndex - 1) * avg + 1;
        // 结束数
        int end = shardIndex * avg;
        logger.info("开始" + start + "结束" + end);
        List<Integer> lists = new ArrayList<>();
        for (int i = start; i <= end; i++) {
            lists.add(i);
        }
        long startTime = System.currentTimeMillis() / 1000;
        jobUserService.removeByIds(lists);
        long endTime = System.currentTimeMillis() / 1000;
        logger.info("耗时" + (endTime - startTime) + "秒");
        return SUCCESS;
    }
}
